package com.core.initialize;

import org.apache.log4j.Logger;

import com.core.NetChannel;
import com.google.protobuf.GeneratedMessage;
/**
 * 前后端通讯用的消息体
 * @author King
 *
 */
public class Message
{
	protected static final Logger log = Logger.getLogger(Message.class);
	
	public final static int CLIENTMIN_LENGTH = 5;
//	private final static MyMessage message = new MyMessage();
	
	public static boolean debug =true;
	
	/** 模块id **/
	protected short module;
	/** 行为id **/
	protected short action;
	/** 加密方式 **/
	protected byte encrypt;
	/**netty的channel**/
	protected NetChannel channel;

	protected Object body;

//	private static final ThreadLocal<Message> threadLocal = new ThreadLocal<Message>();
	
	/**
	 * 在写业务的时候不要使用该方法方便扩展
	 * 替代方案{@link Message#newMessage()}
	 */
	protected Message()
	{
		
	}
	
	@SuppressWarnings("unchecked")
	public <T extends Object> T getBody() {
		return (T) body;
	}
	
	/**获取一个新message**/
	public static Message newMessage()
	{
//		MyMessage msg = threadLocal.get();
//		if(msg==null)
//		{
//			msg = new MyMessage();
//			threadLocal.set(msg);
//		}else
//			msg.clearDate();
		return new Message();
//		return new MyMessage();
//		if(debug)
//		{
//			return new MyMessage();
//		}
//		message.clearData();
//		return message;
	}	

	public byte getEncrypt() {
		return encrypt;
	}

	public void setModuleAction(int module,int action)
	{
		setModule(module);
		setAction(action);
	}
	
	public void setEncrypt(byte encrypt) {
		this.encrypt = encrypt;
	}


	public short getModule() {
		return module;
	}


	protected void setModule(int module) {
		this.module = (short)module;
	}


	public short getAction() {
		return action;
	}


	protected void setAction(int action) {
		this.action = (short)action;
	}

	/**
	 * 尽量不要用此方法 (可以使用  多态方法) 此方法可能是线程不安全的
	 * 业务中使用{@link Message#setBody(com.google.protobuf.GeneratedMessage.Builder)}
	 * @param body
	 */
	protected void setBody(Object body)
	{
		this.body = body;
	}

	@SuppressWarnings("rawtypes")
	public void setBody(GeneratedMessage.Builder builder)
	{
		this.body = builder.build();
	}
	
	public NetChannel getChannel() {
		return channel;
	}

	public void setChannel(NetChannel channel) {
		this.channel = channel;
	}

	/**清除数据**/
	public void clearDate()
	{
		this.module = 0;
		this.action = 0;
		this.encrypt = 0;
		this.body = null;
	}
}
